package it.softphone.cmc.client.entity;

import it.softphone.cmc.shared.entity.Attributes;
import it.softphone.cmc.shared.entity.HasAttributes;

import java.util.logging.Logger;

import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.web.bindery.autobean.shared.AutoBean;

/**
 * 
 * @author bsorrentino
 *
 */
public class AttributesCategory {

	static final Logger logger = Logger.getLogger(AttributesCategory.class.getName());

	/**
	 * 
	 * @param sv
	 * @return
	 */
	private static com.google.gwt.json.client.JSONObject objectFromString( String sv ) {
		
		if( null==sv ) return null;
		
		JSONValue v = JSONParser.parseLenient(sv);
		
		if( v == null ) return null;
		
		if( v.isNull()!=null ) return null;
		
		JSONObject s = v.isObject();
		
		if( s == null ) {
			throw new JSONException("value doesn't contain a JSON object representation!" );
		}
		
		return s;
		
	}	
	
	/**
	 * 
	 * @param <T>
	 * @param instance
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T encodeAttributes(AutoBean<? extends HasAttributes> instance) {

		Attributes attrs = instance.as().getAttributes();

		if( attrs == null ) {
			AutoBean<Attributes> bean = instance.getFactory().create(Attributes.class);
			attrs = bean.as();
			instance.as().setAttributes( attrs );
		}
		com.google.gwt.json.client.JSONObject object = objectFromString(attrs.getJSonPayload());

		return (T)object;

	}

	/**
	 * 
	 * @param instance
	 * @param map
	 */
	public static void decodeAttributes(AutoBean<? extends HasAttributes> instance, Object object) {

		Attributes attrs = instance.as().getAttributes();

		if( attrs == null ) {
			AutoBean<Attributes> bean = instance.getFactory().create(Attributes.class);
			attrs = bean.as();
			instance.as().setAttributes( attrs );
		}

		attrs.setUpdated(new java.util.Date());
		attrs.setJSonPayload(String.valueOf(object));

	}

}
